package com.kehao.leetcode.hard.array;

import org.junit.Test;

import java.util.Arrays;

public class GameOfLifeSolution {
    //位运算大法好
    public void gameOfLife(int[][] board) {
        for (int i = 0; i < board.length; i++) {
            for (int j = 0; j < board[0].length; j++) {
                board[i][j] = board[i][j]<<1;
            }
        }
        for (int i = 0; i < board.length; i++) {
            for (int j = 0; j < board[0].length; j++) {
                int liveCount =0 ;
                for (int k = i-1; k <= i+1; k++) {
                    for (int l = j-1; l <= j+1; l++) {
                        if((k!=i || l!=j) && k>=0 && k<board.length && l>=0 && l<board[0].length){
                            if(board[k][l]>>1==1){
                                liveCount ++;
                            }
                        }
                    }
                }
                if(liveCount<2 || liveCount>3){
                    board[i][j] = board[i][j] | 0;
                }else if(liveCount ==2 ){
                    board[i][j] = board[i][j] | board[i][j]>>1;
                }else if(liveCount ==3 ){
                    board[i][j] = board[i][j] | 1;
                }
            }
        }
        for (int i = 0; i < board.length; i++) {
            for (int j = 0; j < board[0].length; j++) {
                board[i][j] = board[i][j] & 1;
            }
        }
    }

    @Test
    public void test01(){
        int[][] board = {{0,1,0},{0,0,1},{1,1,1},{0,0,0}};
        gameOfLife(board);
        Arrays.stream(board).forEach(i->{
            for (int j = 0; j < i.length; j++) {
                System.out.print(i[j]+" ");
            }
            System.out.println();
        });
    }

    @Test
    public void test02(){
        int[][] board = {{1,1},{1,0}};
        gameOfLife(board);
        Arrays.stream(board).forEach(i->{
            for (int j = 0; j < i.length; j++) {
                System.out.print(i[j]+" ");
            }
            System.out.println();
        });
    }

}
